#include "ConfigGUI.h"
#include "ui_ConfigGUI.h"
#include <QMouseEvent>
#include <QRect>
#include "../config_client/XConfigClient.h"
#include <xplatform/protobuf/xmsg_com.pb.h>
#include <xplatform/XTools.h>
#include <QPlainTextEdit>
#include "ConfigEdit.h"
#include <QString>
using namespace std;
ConfigGUI::ConfigGUI(QWidget *parent) : QWidget(parent),
                                        ui(new Ui::ConfigGUI)
{
    ui->setupUi(this);
    XConfigClient::Get()->SaveConfigResCBFunc=std::bind(&ConfigGUI::saveConfigCB,this,std::placeholders::_1,std::placeholders::_2);
    setWindowFlags(Qt::FramelessWindowHint); // 设置窗口为无边框
    // 设置窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground);
    setMouseTracking(true);
    ui->lineEdit->setText("127.0.0.1");
    ui->spinBox->setValue(CONFIG_PORT);
    XConfigClient::Get()->StartGetConfig("127.0.0.1", CONFIG_PORT, 0, 0, 0);
    connect(ui->btnRefresh, &QPushButton::clicked, this, &ConfigGUI::onBtnRefresh);
    connect(ui->btnAddConfig, &QPushButton::clicked, this, &ConfigGUI::onBtnAddConfig);
    connect(this, &ConfigGUI::windowTitleChanged, this, [this](const QString &title)
            { ui->title->setText(title); });
    connect(this, &ConfigGUI::windowIconChanged, this, [this](const QIcon &icon)
            { ui->labelIcon->setPixmap(icon.pixmap(QSize(20, 20))); });
    connect(ui->normalButton, &QPushButton::clicked, this, &ConfigGUI::onNormalButtonClicked);
    connect(ui->maxisizeButton, &QPushButton::clicked, this, &ConfigGUI::onMaximizeButtonClicked);
    connect(ui->btnDelConfig, &QPushButton::clicked, this, &ConfigGUI::onBtnDelConfig);
    connect(ui->btnEditConfig, &QPushButton::clicked, this, &ConfigGUI::onBtnEditConfig);
    ui->normalButton->clicked();
    onBtnRefresh();
}

ConfigGUI::~ConfigGUI()
{
    delete ui;
}

void ConfigGUI::AddLog(const QString &log)
{
    ui->plainTextEdit->appendPlainText(log);
    ui->plainTextEdit->moveCursor(QTextCursor::End);
}

void ConfigGUI::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        m_bMousePress = true;
        m_ptLocalPress = event->position().toPoint();
        m_ptPress = event->globalPosition().toPoint();
        m_resizeDirection = getResizeDirection(event);
        m_originalGeometry = this->geometry();
        return;
    }
    QWidget::mousePressEvent(event);
}
ConfigGUI::ResizeDirection ConfigGUI::getResizeDirection(const QMouseEvent *event)
{
    int borderSize = 5;
    QRect rect = this->geometry();
    QRect topRect(rect.left(), rect.top(), rect.width(), borderSize);
    QRect bottomRect(rect.left(), rect.bottom() - borderSize, rect.width(), borderSize);
    QRect leftRect(rect.left(), rect.top(), borderSize, rect.height());
    QRect rightRect(rect.right() - borderSize, rect.top(), borderSize, rect.height());
    QRect topLeftRect(rect.left(), rect.top(), borderSize, borderSize);
    QRect topRightRect(rect.right() - borderSize, rect.top(), borderSize, borderSize);
    QRect bottomLeftRect(rect.left(), rect.bottom() - borderSize, borderSize, borderSize);
    QRect bottomRightRect(rect.right() - borderSize, rect.bottom() - borderSize, borderSize, borderSize);
    auto pos = event->globalPosition().toPoint();
    if (topLeftRect.contains(pos))
        return TopLeft;
    else if (topRightRect.contains(pos))
        return TopRight;
    else if (bottomLeftRect.contains(pos))
        return BottomLeft;
    else if (bottomRightRect.contains(pos))
        return BottomRight;
    else if (topRect.contains(pos))
        return Top;
    else if (bottomRect.contains(pos))
        return Bottom;
    else if (leftRect.contains(pos))
        return Left;
    else if (rightRect.contains(pos))
        return Right;
    else if (ui->widgetHeader->geometry().contains(event->position().toPoint()))
        return Move;
    return None;
}

void ConfigGUI::ddd(ResizeDirection r)
{
    switch (r)
    {
    case TopLeft:
    case BottomRight:
        setCursor(Qt::SizeFDiagCursor);
        break;
    case TopRight:
    case BottomLeft:
        setCursor(Qt::SizeBDiagCursor);
        break;
    case Left:
    case Right:
        setCursor(Qt::SizeHorCursor);
        break;
    case Top:
    case Bottom:
        setCursor(Qt::SizeVerCursor);
        break;
    case Move:
    case None:
        setCursor(Qt::ArrowCursor);
        break;
    }
}

void ConfigGUI::saveConfigCB(bool isOk, const std::string &msg)
{
    qDebug()<<QString(msg.c_str());
    ui->plainTextEdit->appendPlainText(QString(msg.c_str()));
}

void ConfigGUI::mouseMoveEvent(QMouseEvent *event)
{
    if (m_bMousePress)
    {
        QPoint ptMove = event->globalPosition().toPoint() - m_ptPress;
        QRect newGeometry = m_originalGeometry;
        // ddd(m_resizeDirection);
        switch (m_resizeDirection)
        {
        case TopLeft:
            newGeometry.setTopLeft(m_originalGeometry.topLeft() + ptMove);
            break;
        case TopRight:
            newGeometry.setTopRight(m_originalGeometry.topRight() + ptMove);
            break;
        case BottomLeft:
            newGeometry.setBottomLeft(m_originalGeometry.bottomLeft() + ptMove);
            break;
        case BottomRight:
            newGeometry.setBottomRight(m_originalGeometry.bottomRight() + ptMove);
            break;
        case Left:
            newGeometry.setLeft(m_originalGeometry.left() + ptMove.x());
            break;
        case Right:
            newGeometry.setRight(m_originalGeometry.right() + ptMove.x());
            break;
        case Top:
            newGeometry.setTop(m_originalGeometry.top() + ptMove.y());
            break;
        case Bottom:
            newGeometry.setBottom(m_originalGeometry.bottom() + ptMove.y());
            break;
        case Move:
            move(event->globalPosition().toPoint() - m_ptLocalPress);
            return;
        case None:
            return QWidget::mouseMoveEvent(event);
        }
        setGeometry(newGeometry);
        return;
    }
    // auto resizeDirection = getResizeDirection(event);
    // ddd(resizeDirection);
    QWidget::mouseMoveEvent(event);
}

void ConfigGUI::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        m_bMousePress = false;
        m_resizeDirection = None;
    }
    QWidget::mouseReleaseEvent(event);
}

void ConfigGUI::onBtnAddConfig()
{
    ConfigEdit edit = ConfigEdit(this);
    edit.setWindowIcon(this->windowIcon());
    connect(&edit, &ConfigEdit::AddLog, this, &ConfigGUI::AddLog);
    connect(&edit, &ConfigEdit::MessageCBSig, this, [this](bool is_ok, const char *msg)
            {
        if(is_ok){
            AddLog(msg);
            onBtnRefresh();
        }else{
            AddLog(QString("保存失败:")+msg);
        } });
    edit.exec();
}

void ConfigGUI::onBtnDelConfig()
{
    int row = ui->tableWidget->currentRow();
    if (row < 0 || row >= ui->tableWidget->rowCount())
    {
        return;
    }
    std::string ip = ui->tableWidget->item(row, 1)->text().toStdString();
    int port = ui->tableWidget->item(row, 2)->text().toInt();
    XConfigClient::Get()->DeleteConfig(ip.c_str(), port);
}
void ConfigGUI::onBtnEditConfig()
{
    int row = ui->tableWidget->currentRow();
    if (row < 0 || row >= ui->tableWidget->rowCount())
    {
        return;
    }
    std::string ip = ui->tableWidget->item(row, 1)->text().toStdString();
    int port = ui->tableWidget->item(row, 2)->text().toInt();
    ConfigEdit edit = ConfigEdit(this);
    edit.setWindowIcon(this->windowIcon());
    bool ret = edit.LoadConfig(ip.c_str(), port);
    if(!ret){
        return;
    }
    if (edit.exec() == QDialog::Accepted)
    {
        AddLog("修改配置成功");
        onBtnRefresh();
    }
    //XConfigClient::Get()->LoadConfig(ip.c_str(), port);
}
void ConfigGUI::onNormalButtonClicked()
{
    ui->normalButton->setHidden(true);
    ui->maxisizeButton->setHidden(false);
}
void ConfigGUI::onMaximizeButtonClicked()
{
    ui->normalButton->setHidden(false);
    ui->maxisizeButton->setHidden(true);
}

void ConfigGUI::onBtnRefresh()
{
    ui->tableWidget->clear();
    string ip = ui->lineEdit->text().toStdString();
    if (ip.empty())
    {
        ip = "127.0.0.1";
    }
    int port = ui->spinBox->value();
    XConfigClient::Get()->setServerIP(ip.c_str());
    XConfigClient::Get()->setServerPort(port);
    if (!XConfigClient::Get()->Close())
    {
        return;
    }
    if (!XConfigClient::Get()->autoConnect(3))
    {
        AddLog("连接失败");
        return;
    }
    AddLog("连接成功");
    auto f = XConfigClient::Get()->GetAllConfig(1, 100);
    auto &configs = f.config();
    ui->tableWidget->setRowCount(configs.size());
    int i = 0;
    for (auto &config : configs)
    {
        ui->tableWidget->setItem(i, 0, new QTableWidgetItem(QString::fromStdString(config.service_name())));
        ui->tableWidget->setItem(i, 1, new QTableWidgetItem(QString::fromStdString(config.service_ip())));
        ui->tableWidget->setItem(i, 2, new QTableWidgetItem(QString::number(config.service_port())));
        i++;
    }
    // XConfigClient::Get()->GetAllConfig(ip.c_str(), port);
}
